#!/bin/bash
#
# Usage:
#   ./do.sh <action>

banner() {
  echo 1>&2
  echo 1>&2 --- $@ ---
  echo 1>&2
}

# command line tool
tnet() {
  PYTHONPATH=.. ../bin/tnet.py "$@"
}

makeheaders() {
  gcc -o makeheaders makeheaders.c && ./makeheaders "$@"
}

run() {
  gcc -o tnet_test tnet.c tnet_test.c && ./tnet_test "$@"
}

pgi-app() {
  gcc -o app tnet.c pgi.c app.c && ./app "$@"
}

clang-ast() {
  rm *.ast
  set -o errexit
  # my clang 2.8 version (from Ubuntu) has -emit-ast (online docs say -ast-dump
  # or -ast-print, which seem to do nothing)
  clang -emit-ast tnet.c pgi.c app.c
  #clang++ -ast-dump tnet.c pgi.c app.c
  ls *.ast
}

demo() {
  set -o errexit
  run dump-dict

  echo
  echo '-------- READING'
  echo
  tnet echo .hello | run read
}

read-dict() {

  echo
  echo '-------- READING DICT'
  echo
  tnet echo { .foo .bar } | run read-dict

  tnet echo { .foo .blah .xxx .yyy } | run read-dict

}

pgi-test() {
  set -o errexit

  # embed JSON in the TNET request
  local json='{"str": "x", "blah": 10}'

  banner Ping

  tnet echo { .command .init  .format .tnet } \
    | pgi-app \
    | tnet view

  banner Request

  # Echo request through pgi.go, output response as JSON
  tnet echo { .route .Echo  .request ."$json" } \
    | pgi-app \
    | tnet view

}


build-cpp() {
  set -o errexit
  mkdir -p cpp
  protoc --cpp_out cpp "$@"
  tree cpp
}

gen-dispatch() {
  PYTHONPATH=../../json-template/python ./gen_dispatch.py "$@"
}

# Ubuntu has a package 'protobuf-compiler', which doesn't let you build
# generated C++?  Need libprotobuf-dev / libprotoc-dev.
#
# Weirdness:
#
# On Google machines I Need to do -lpthread?  The protocol compiler generates
# some code that links against pthreads?  Just added it here.


build-example() {
  set -o errexit

  # Output generated code in cpp/ dir
  build-cpp example/echo.proto 1>&2

  # TODO: Applet name and handlers come from APP file.  Namespace comes from the
  # proto file.  The proto namespace should match the C++ code namespace.
  gen-dispatch \
    --out-dir cpp/example \
    --applet-name Echo \
    --namespace tutorial \
    --handlers Index,Echo

  # Compile generated code with demo.  Add cpp to include path, link with
  # libprotobuf.a.
  g++ -o example/echo \
    -Icpp \
    -I. \
    -lprotobuf \
    -lpthread \
    pgi.c \
    tnet.c \
    cpp/example/echo.pb.cc \
    cpp/example/dispatch.gen.cc \
    example/echo.cc
}


run-example() {
  set -o errexit

  build-example

  banner Ping

  tnet echo { .command .init } \
    | example/echo \
    | tnet view

  banner Request

  tnet echo { .route .Echo .request .PROTO } \
    | example/echo \
    | tnet view

  banner No Route

  tnet echo { .request .PROTO } \
    | example/echo
}


"$@"
